﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using RepositoryTestWeb.AppService;
using System;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;

namespace RepositoryTestWeb.Controllers
{
    public class UserController : ControllerBase
    {
        private readonly IUserService _userService;

        public UserController(IUserService userService)
        {
            this._userService = userService;
        }

        [HttpGet]
        [AllowAnonymous]
        public async Task<IActionResult> Get()
        {
            var userDots = await this._userService.GetAllAsync();
            var userDotsFromCache = await this._userService.GetAllFromCacheAsync();

            return Json(userDots);
        }

        [HttpGet("{name}")]
        public async Task<IActionResult> Get(string name)
        {
            var result = await this._userService.GetByUserNameAsync(name);

            var claims = User.Claims?.ToList();

            return Json(new
            {
                result = result,
                claims = new
                {
                    Id = (claims ?? throw new InvalidOperationException()).FirstOrDefault(c => c.Type == ClaimTypes.Sid)?.Value,
                    UserName = claims.FirstOrDefault(c => c.Type == ClaimTypes.Name)?.Value,
                    Roles = claims.FirstOrDefault(c => c.Type == ClaimTypes.Role)?.Value
                }
            });
        }

        [HttpPost]
        [AllowAnonymous]
        public async Task<IActionResult> Post([FromBody]UserDto input)
        {
            var result = await this._userService.AddAsync(input);

            return Json(result);
        }

        [HttpPut]
        [AllowAnonymous]
        public async Task<IActionResult> Put([FromBody]UserDto input)
        {
            var result = await this._userService.UpdateAsync(input);

            return Json(result);
        }

        [HttpPut("{id}")]
        [AllowAnonymous]
        public async Task<IActionResult> Put(Guid id)
        {
            var dto = await this._userService.GetByIdAsync(id, false);
            var dtoFromCache = await this._userService.GetByIdFromCacheAsync(id, false);
            var result = await this._userService.SoftDeleteAsync(dto);

            return Json(result);
        }

        [HttpDelete("{id}")]
        [AllowAnonymous]
        public async Task<IActionResult> Delete(Guid id)
        {
            var dto = await this._userService.GetByIdAsync(id);
            var result = await this._userService.DeleteAsync(dto);

            return Json(result);
        }
    }
}